CROSS_COMPILE := riscv64-unknown-elf-
CC := $(CROSS_COMPILE)gcc
LD := $(CROSS_COMPILE)ld
OBJCOPY := $(CROSS_COMPILE)objcopy
OBJDUMP := $(CROSS_COMPILE)objdump

SRC_DIR := $(CURDIR)
BUILD_DIR := $(SRC_DIR)/build

C_SRC := $(shell find $(SRC_DIR) -name "*.c")
ASM_SRC := $(shell find $(SRC_DIR) -name "*.S")
OBJS := $(patsubst $(SRC_DIR)/%.S, $(BUILD_DIR)/%.o, $(ASM_SRC))
OBJS += $(patsubst $(SRC_DIR)/%.c, $(BUILD_DIR)/%.o, $(C_SRC))

CFLAGS := -mcmodel=medany -std=gnu99 -Wall -Werror -Wno-unused
CFLAGS += -fno-builtin -ffreestanding -nostdinc
CFLAGS += -fno-stack-protector -ffunction-sections -fdata-sections
CFLAGS += -I.

LDFLAGS := -m elf64lriscv -nostdlib --gc-sections
LD_SCRIPT := qemu-opensbi.ld

NAME := rtos
ELF := $(BUILD_DIR)/$(NAME).elf
IMG := $(BUILD_DIR)/$(NAME).img
FULL_ASM := $(BUILD_DIR)/$(NAME).asm

all: $(IMG)

$(IMG): $(ELF)
	$(OBJCOPY) $< --strip-all -O binary $@

$(ELF): $(OBJS)
	$(LD) $^ -o $@ $(LDFLAGS) -T $(LD_SCRIPT)
	$(OBJDUMP) -D $@ > $(FULL_ASM)

$(BUILD_DIR)/%.o: $(SRC_DIR)/%.S
	@mkdir -p $(dir $@)
	$(CC) $(CFLAGS) -x assembler-with-cpp -c $< -o $@

$(BUILD_DIR)/%.o: $(SRC_DIR)/%.c
	@mkdir -p $(dir $@)
	$(CC) $(CFLAGS) -c $< -o $@

QEMU := qemu-system-riscv64
QEMU_FLAGS := -smp 1 -machine virt -bios default -m 128M -nographic
QEMU_LOAD_ADDR := 0x80200000

qemu: $(IMG)
	$(QEMU) $(QEMU_FLAGS) -kernel $(ELF)

clean:
	rm -rf $(BUILD_DIR)

.PHONY: all qemu clean